package ophiux.wechatpay.sdk.common.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 文件名称:XMLUtil<br>
 * 内容摘要:MAP转为XML格式<br>
 * 接口说明：<br>
 * <h1>创 建 人: hhl<br>
 * </h1> 创建日期: 2017-7-3上午9:38:05<br>
 * 修改记录1: // 修改历史记录，包括修改日期、修改者及修改内容<br>
 * 修改日期： 版 本 号： 修 改 人： 修改内容： 修改记录2：…
 * 
 */
public class MapToXMLUtil {

	private static final int DEFAULT_BUFFER_SIZE = 1024;

	/**
	 * 读取xml文件
	 * @param file
	 * @param encoding
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String getXmlStringFromFile(String file, String encoding) {

		InputStreamReader reader = null;
		StringWriter writer = new StringWriter();
		try {
			if (encoding == null || "".equals(encoding.trim())) {
				reader = new InputStreamReader(new FileInputStream(file),
						encoding);
			} else {
				reader = new InputStreamReader(new FileInputStream(file));
			}

			char[] buffer = new char[DEFAULT_BUFFER_SIZE];
			int n = 0;
			while (-1 != (n = reader.read(buffer))) {
				writer.write(buffer, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		// 返回转换结果
		if (writer != null)
			return writer.toString();
		else
			return null;
	}

	/**
	 * 将Map转换为Xml字符串 Map的键与xml的节点名一致
	 * 
	 * @param map
	 */
	public static String mapToXml(Map<String, String> map) {

		if (map == null) {
			return "";
		}
		StringBuffer xmlStr = new StringBuffer();
		for (String key : map.keySet()) {
			String value = map.get(key);
			if (StringUtil.isEmpty(value)) {
				continue;
			}
			xmlStr = buildXml(xmlStr, key, value);
		}
		return xmlStr.toString();
	}

	/**
	 * 组装xml
	 * @param xmlStr 数据源xml
	 * @param nodeName 待组装xml节点名
	 * @param value 待组装xml值
	 * @return 组装后的xml
	 */
	public static StringBuffer buildXml(StringBuffer xmlStr, String nodeName,
			String value) {
		if (StringUtil.isEmpty(value)) {
			value = "";
		}
		xmlStr.append("<" + nodeName + ">").append(value)
				.append("</" + nodeName + ">");
		return xmlStr;
	}

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("dd", "234");
		map.put("dddd", "sdf");
		System.out.println(MapToXMLUtil.mapToXml(map));
	}

}
